/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Model.DataSource;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

/**
 *
 * @author ngoc
 */
public class SpeakingDAO implements DAOImpl<Speaking>{

    public int getMaxId()
    {
        int num = 0;
        DataSource s = new DataSource();
        Connection conn = s.getconnectToMSSQL();
        Statement stm  = null;
        ResultSet rs = null;
        List<Reading> readingList = new ArrayList<Reading>();
        try {
            
            String query = "select max(SpeakingID)as IdMax from Speaking ";
            stm = conn.createStatement();
            rs = stm.executeQuery(query);
            while(rs.next())
            {
                num = num+rs.getInt("IdMax");
            }
        } catch (SQLException ex) {
            Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally{
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return num;
    }
    
    @Override
    public List<Speaking> getAll() {
        DataSource s = new DataSource();
        Connection conn = s.getconnectToMSSQL();
        Statement stm  = null;
        ResultSet rs = null;
        List<Speaking> speakingList = new ArrayList<Speaking>();
        try {
            
            String query = "SELECT SpeakingID,SpeakingName,UrlSpeaking,UrlTime,UrlHistory FROM Speaking";
            stm = conn.createStatement();
            rs = stm.executeQuery(query);
            while(rs.next())
            {
                Speaking speaking = new Speaking();
                speaking.setSpeakingID(rs.getInt("SpeakingID"));
                speaking.setSpeakingname(rs.getString("SpeakingName"));
                speaking.setUrlSpeaking(rs.getString("UrlSpeaking"));
                speaking.setUrlTime(rs.getString("UrlTime"));
                speaking.setUrlHistory(rs.getString("UrlHistory"));
                speakingList.add(speaking);
            }
        } catch (SQLException ex) {
            Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally{
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return speakingList;
    }

    @Override
    public void add(Speaking speaking) {
       DataSource s = new DataSource();
        Connection conn = s.getconnectToMSSQL();
        Statement stm  = null;
        ResultSet rs = null;
        int id = speaking.getSpeakingID();
        try {
            
            String query = "insert into Speaking(SpeakingID,SpeakingName,UrlSpeaking,UrlTime,UrlHistory) values ("+id+",'"+speaking.getSpeakingname()+"', '"+speaking.getUrlSpeaking()+"' , '"+speaking.getUrlTime()+"', '"+speaking.getUrlHistory()+"')";           
            stm = conn.createStatement();
            stm.execute(query);
        } catch (SQLException ex) {
            Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally{
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public Speaking getReading(int ID) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void update(Speaking reading) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void delete(Speaking reading) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    
    
    public String[] readUsingBufferedReader(String fileName, Charset cs)
        throws IOException {
        File fi = new File("DeTai\\FileSpeaking\\"+fileName);
        String a = fi.getAbsolutePath();
        File file = new File(a);
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis, cs);
        BufferedReader br = new BufferedReader(isr);
        String line;
        int coutline = countLines(fileName)+1;
        
        String[] afile1 = new String[coutline];
        String[] afile2 = new String[coutline];
        int iDongThu = -1;
        while ((line = br.readLine()) != null) {
           // process the line
           iDongThu++;
           afile1[iDongThu] = line;
           //System.out.println(afile1[iDongThu]);
        }
        br.close();
        return afile1;
    }
    
    ////
    public int countLines(String filename) throws IOException {
    File fi = new File("DeTai\\FileSpeaking\\"+filename);
    String a = fi.getAbsolutePath();
    InputStream is = new BufferedInputStream(new FileInputStream(a));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
            //System.out.println("tong so dong: "+count);
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
    }
    
    public void PlayAudio(){
            // open the sound file as a Java input stream
    String gongFile = "~tmp1.wav";
    InputStream in = null;
        try {
            in = new FileInputStream(gongFile);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(SpeakingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
 
    // create an audiostream from the inputstream
    AudioStream audioStream = null;
        try {
            audioStream = new AudioStream(in);
        } catch (IOException ex) {
            Logger.getLogger(SpeakingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
 
    // play the audio clip with the audioplayer class
    AudioPlayer.player.start(audioStream);
    }
    
    public void SaveFile(String string, String filename) 
    {
       FileOutputStream os = null;
        try {
            os = new FileOutputStream ("DeTai\\FileSpeaking\\"+filename,true);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(SpeakingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(os);

            String s= string;
            pw.println(s);
        pw.close();
        try {
            os.close();
        } catch (IOException ex) {
            Logger.getLogger(SpeakingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public String readFile(String url)
    {
       String file = "";
       FileInputStream f = null;
        try {
            File fi = new File("DeTai\\FileSpeaking\\"+url);
            String a = fi.getAbsolutePath();
            f = new FileInputStream(a);
        } catch (FileNotFoundException exc) {
            System.out.println("File Not Found");
            
            //return;
        } catch (ArrayIndexOutOfBoundsException exc) {
            System.out.println("Usage: ShowFile File");
            //return;
        }
        // Đọc cho tới cuối file
        int i = 0;
        do {
           try {
               i = f.read();
           } catch (IOException ex) {
               Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
           }
            if (i != -1) {
                file += (char) i;
            }
        } while (i != -1);
        try {
            f.close();
        } catch (IOException ex) {
            Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
       return file;
    }
    public void infoBox(String infoMessage, String titleBar)
    {
        JOptionPane.showMessageDialog(null, infoMessage,titleBar, JOptionPane.INFORMATION_MESSAGE);
    }
    
    public void CoppyFile(String filein, String fileout){
        FileInputStream fin;
        FileOutputStream fout;
        String urlout = "DeTai\\FileSpeaking\\"+fileout;
        try {// open input file
            try {
                fin = new FileInputStream(filein);
            } catch (FileNotFoundException exc) {
                System.out.println("Input File Not Found");
                return;
            }
 // open output file
            try {
                fout = new FileOutputStream(urlout);
            } catch (FileNotFoundException exc) {


                System.out.println("Error Opening OutputFile ");
                return;
            }
        } catch (ArrayIndexOutOfBoundsException exc) {
            System.out.println("Usage: CopyFile From To");
            return;
        }
    // Copy File
        int i;
        try {
            do {
                i = fin.read();
                if (i != -1) {
                    fout.write(i);
                }
            } while (i != -1);
        } catch (IOException exc) {
            System.out.println("File Error");
        }
        ///close fin and fout
        try {
            fin.close();
            fout.close();
        } catch (IOException ex) {
            Logger.getLogger(SpeakingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    public void DeleteFile(String url){
        try {
       File file = new File("DeTai\\FileSpeaking\\"+url);
       System.out.println("DeTai\\FileSpeaking\\"+url);
       if (file.delete()) {
           System.out.println(file.getName() + " is deleted!");
       } else {
           System.out.println("Deleteation is failed.");
       }
        } catch (Exception e) {
           e.printStackTrace();
        }
    }
}
